home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 108 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  940 b 

  1. From: maven@mavenry.altcit.eskimo.com (Norman Hamer)
  2. Message-ID: <646916@mavenry.altcit.eskimo.com>
  3. Path: news.sprintlink.net!eskimo!mavenry
  4. Newsgroups: comp.std.c
  5. Subject: Safe Multiply, std ok.
  6. X-AltCit-ID: 646916
  7. Date: Thu, 11 Jan 96 15:04:37 GMT
  8.  
  9.  
  10.  Daniel- Sure there's a way. It's slow and evil (at least in this 
  11. incarnation), but it makes a lot more sense for floats...
  12.  
  13.  #include <math.h>
  14.  #include <limits.h>
  15.  
  16.  int bad_mult(int num1, int num2)
  17.  {
  18.       return (log(abs(num1)) * log(abs(num2)) > log(INT_MAX)) ? 1 : 0;
  19.  }
  20.  
  21.  ... now, this'll give one false negative (if the two numbers multiply to 
  22. produce INT_MIN on a 2's complement machine or something where INT_MIN isn't 
  23. real close in magnitude to INT_MAX), but that could be taken care of by 
  24. slight additional code to check signs and compare against log(abs(INT_MIN)) 
  25. if necessary.
  26.  
  27.  On the other hand, this is really going to slow down simple integer 
  28. multiplies. ;) 
  29.